package com.huan;


import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//使用jdk提供的工具类开发客户端
public class Test8_url_urlconnection_httpurlconnection {
    final static Logger logger = Logger.getLogger(Test8_url_urlconnection_httpurlconnection.class.getName());
    public static void main(String[] args) throws IOException {
        //1.URL 统一资源定位符
//        URL url = new URL("http://www.baidu.com");
//        URLConnection connection = url.openConnection();
//        String connectionType = connection.getContentType();
//        long conlength = connection.getContentLength();
//        logger.info(connectionType+"\t"+conlength);
//
//        //响应头内容被解析成了connection中的属性值
//
//        InputStream inputStream = connection.getInputStream();
//        byte[] bytes = new byte[10*1024];
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        int length = -1;
//        while ((length= inputStream.read(bytes,0,bytes.length))!=-1){
//            byteArrayOutputStream.write(bytes,0,length);
//        }
//        byteArrayOutputStream.flush();
//        byte[] b = byteArrayOutputStream.toByteArray();
//
//        String s = new String(b);
//        System.out.println(s);

        //URL+HTTPURLConnection
        URL url = new URL("http://www.baidu.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("HOST","www.baidu.com");
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0");
        connection.setDoOutput(true);
        connection.setDoInput(true);

        String contenType = connection.getContentType();
        long conlength = connection.getContentLengthLong();
        logger.info(contenType+"\t"+conlength);

        InputStream inputStream = connection.getInputStream();
        byte[] bytes = new byte[10*1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int length = -1;
        while ((length= inputStream.read(bytes,0,bytes.length))!=-1){
            byteArrayOutputStream.write(bytes,0,length);
        }
        byteArrayOutputStream.flush();
        byte[] b = byteArrayOutputStream.toByteArray();

        String s = new String(b);
        System.out.println(s);
    }
}
